<script lang="tsx">
  import { computed, defineComponent, PropType, ref, unref, watch } from 'vue'
  import { FormSchema, ComponentNameEnum } from './index'
  import { componentMap } from './helper/componentMap'
  import { ElForm } from 'element-plus'
  import { set, get } from 'lodash-es'
  export default defineComponent({
    name: 'Form',
    props: {
      schema: {
        type: Array as PropType<FormSchema[]>,
        default: () => [],
      },
      model: {
        type: Object as PropType<any>,
        default: () => ({}),
      },
    },
    setup(props) {
      const elFormRef = ref<InstanceType<typeof ElForm>>()
      const getProps = computed(() => {
        const propsObj = { ...props }
        // Object.assign()
        return propsObj
      })
      const formModel: any = ref<Record<string, any>>(props.model)

      watch(
        () => unref(getProps).schema,
        (schema = []) => {
          formModel.value = initModel(schema, unref(formModel))
        },
        {
          immediate: true,
          deep: true,
        }
      )
      function renderWrap() {
        renderFormItemWrap()
      }

      function getOptions(api: string, item: FormSchema) {
        // const options = await api()
        // item.options = options
      }

      function initModel(schema: FormSchema[], formModel: Record<string, any>) {
        const model: Record<string, any> = { ...formModel }
        schema.map((v) => {
          const hasField = get(model, v.field)
          set(model, v.field, hasField !== void 0 ? get(model, v.field) : v.value !== void 0 ? v.value : undefined)
        })
      }

      function renderFormItem(item: FormSchema) {
        if (item.api) {
          getOptions(item.api, item)
        }
      }

      function renderFormItemWrap() {
        const { schema = [] } = unref(getProps)
        return schema.map((item) => {
          renderFormItem(item)
        })
      }
      // if (unref(getProps).schema.length > 0) {
      //   const { schema } = unref(getProps)
      //   if (ComponentNameEnum.INPUT === schema[0].component) {
      //     const Com = componentMap[ComponentNameEnum.INPUT] as ReturnType<typeof defineComponent>
      //     return () => (
      //       <>
      //         <div class="w-[50px]">{schema[0].label}</div>
      //         <Com vModel={schema[0].field} />
      //       </>
      //     )
      //   }
      // } else {

      // }

      return () => (
        <>
          <ElForm ref={elFormRef}>
            <div>暂无数据</div>
          </ElForm>
        </>
      )
    },
  })
</script>
